/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * jpImportarAsistencias.java
 *
 * Created on 16/10/2011, 11:07:05 PM
 */

package Control;

import administracion.delegate.GestionPedidosDelegate;
import administracion.helper.Utiles_Importar;
import administracion.helper.Utiles_MensajesDialogo;
import java.awt.event.KeyEvent;
import java.io.File;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JInternalFrame;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.joda.time.DateTime;
import org.joda.time.Interval;
import suministros.ejb30.entity.AuxiliarCargarAsistenciaDiaria;

/**
 *
 * @author Renato
 */
public class jpImportarAsistencias extends javax.swing.JPanel {
    private int hojaExcel;
    private ArrayList dat;
    int filas;
    private JInternalFrame padre;
    /** Creates new form jpImportarAsistencias */
    public jpImportarAsistencias() {
        initComponents();
    }

    public void setPadre(JInternalFrame padre){
        this.padre = padre;
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel4 = new javax.swing.JLabel();
        jtfDireccion = new javax.swing.JTextField();
        jbtnSeleccion = new javax.swing.JButton();
        jbtnMigrar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtAsistencias = new javax.swing.JTable();
        jbtnAceptar = new javax.swing.JButton();
        jbtnCancelar = new javax.swing.JButton();

        jLabel4.setFont(new java.awt.Font("Arial", 1, 12));
        jLabel4.setText("UBICACION:");

        jtfDireccion.setFont(new java.awt.Font("Arial", 0, 12));

        jbtnSeleccion.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        jbtnSeleccion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/fife/plaf/Office2003/open.gif"))); // NOI18N
        jbtnSeleccion.setText("SELECCIONAR ARCHIVO");
        jbtnSeleccion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnSeleccionActionPerformed(evt);
            }
        });

        jbtnMigrar.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        jbtnMigrar.setText("MIGRAR DE EXCEL");
        jbtnMigrar.setEnabled(false);
        jbtnMigrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnMigrarActionPerformed(evt);
            }
        });

        jtAsistencias.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "DNI", "NOMBRES", "FECHA", "HORA ENTRADA", "HORA SALIDA", "FERIADO", "DOMINGO/DESCANSO"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Boolean.class, java.lang.Boolean.class
            };
            boolean[] canEdit = new boolean [] {
                true, false, true, true, true, true, true
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jtAsistencias);

        jbtnAceptar.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        jbtnAceptar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/fife/plaf/Office2003/options.gif"))); // NOI18N
        jbtnAceptar.setText("ACEPTAR");
        jbtnAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnAceptarActionPerformed(evt);
            }
        });
        jbtnAceptar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jbtnAceptarKeyPressed(evt);
            }
        });

        jbtnCancelar.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        jbtnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/fife/plaf/Office2003/close.gif"))); // NOI18N
        jbtnCancelar.setText("CERRAR");
        jbtnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnCancelarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 783, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addGap(18, 18, 18)
                        .addComponent(jtfDireccion, javax.swing.GroupLayout.PREFERRED_SIZE, 504, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jbtnSeleccion))
                    .addComponent(jbtnMigrar, javax.swing.GroupLayout.PREFERRED_SIZE, 169, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jbtnAceptar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jbtnCancelar)))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jbtnAceptar, jbtnCancelar});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jtfDireccion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jbtnSeleccion))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbtnMigrar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jbtnCancelar)
                    .addComponent(jbtnAceptar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jbtnSeleccionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnSeleccionActionPerformed
        JFileChooser jfc = new JFileChooser();
        jfc.setAcceptAllFileFilterUsed(false);
        FileNameExtensionFilter fnef= new FileNameExtensionFilter("XLS & ODS","XLS","ODS");
        jfc.setMultiSelectionEnabled( false );
        jfc.setFileFilter(fnef);
        int returnVal = jfc.showOpenDialog( this );
        if( returnVal == JFileChooser.APPROVE_OPTION ){
            this.jtfDireccion.setText( jfc.getSelectedFile().toString() );
            this.jbtnMigrar.setEnabled(true);

        }else{
            this.jtfDireccion.setText( "" );
        }
}//GEN-LAST:event_jbtnSeleccionActionPerformed


    private void limpiarTabla(){
        jtAsistencias.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "DNI", "NOMBRES", "FECHA", "HORA ENTRADA", "HORA SALIDA", "FERIADO", "DOMINGO/DESCANSO"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Boolean.class, java.lang.Boolean.class
            };
            boolean[] canEdit = new boolean [] {
                true, false, true, true, true, true, true
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
    }
    private void jbtnMigrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnMigrarActionPerformed
       limpiarTabla();
        this.cargarExcel();
}//GEN-LAST:event_jbtnMigrarActionPerformed

    private void jbtnAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnAceptarActionPerformed
        try {

            /*********************************************/
            DateTime date1,date2,date3,date4;
            Interval interval1,interval2,interval3;
            date1 = new DateTime(2010, 6, 25, 22, 0, 0, 0);//10 pm hora inicio de nocturno
            date2 = new DateTime(2010, 6, 26, 6, 0, 0, 0);//6 am hora final de nocturno

             interval1 = new Interval(date1, date2);
            /*********************************************/
            List<AuxiliarCargarAsistenciaDiaria> lista=new ArrayList(1);
            List<AuxiliarCargarAsistenciaDiaria> listaERROR=new ArrayList(1);
            AuxiliarCargarAsistenciaDiaria nuevo;
            String dni,hentrada,hsalida;
            StringTokenizer token;
            float h_ordi,h_noctu;
            int h_en,m_en,h_sa,m_sa;

            for (int i=0;i<this.filas;i++){
                dni=this.jtAsistencias.getValueAt(i, 0).toString().trim();
                if(dni.length()<7){
                    dni="00"+dni;
                }else if(dni.length()<8){
                    dni="0"+dni;
                }
                hentrada=this.jtAsistencias.getValueAt(i, 3).toString().trim();
                if(hentrada.length()<5)
                    hentrada="0"+hentrada;

                hsalida=this.jtAsistencias.getValueAt(i, 4).toString().trim();
                if(hsalida.length()<5)
                    hsalida="0"+hsalida;

                token=new StringTokenizer(hentrada,":");
                h_en=Integer.valueOf(token.nextToken().trim());
                m_en=Integer.valueOf(token.nextToken().trim());

                token=new StringTokenizer(hsalida,":");
                h_sa=Integer.valueOf(token.nextToken().trim());
                m_sa=Integer.valueOf(token.nextToken().trim());
                
                date3 = new DateTime(2010, 6, 25, h_en, m_en, 0, 0);
                if(((h_sa*60)+m_sa)<((h_en*60)+m_en)){
                    date4 = new DateTime(2010, 6, 26, h_sa, m_sa, 0, 0);
                }else{
                    date4 = new DateTime(2010, 6, 25, h_sa, m_sa, 0, 0);
                }

                interval2 = new Interval(date3, date4);
                interval3=interval1.overlap(interval2);
                if(interval3==null){
                    h_noctu=0;
                }else{
                    h_noctu=Long.valueOf(interval3.toDuration().getStandardMinutes()).floatValue() /60;
                }
                h_ordi=Long.valueOf(interval2.toDuration().getStandardMinutes()).floatValue() /60;
                h_ordi=h_ordi-h_noctu;
                nuevo=new AuxiliarCargarAsistenciaDiaria(dni,this.jtAsistencias.getValueAt(i, 2).toString().trim());
                nuevo.setHoraEntrada(hentrada);
                nuevo.setHoraSalida(hsalida);
                nuevo.setFeriado(((Boolean)this.jtAsistencias.getValueAt(i, 5)).booleanValue());
                nuevo.setDomingo(((Boolean)this.jtAsistencias.getValueAt(i, 6)).booleanValue());
                nuevo.setH_nocturna(Float.toString(h_noctu));
                nuevo.setH_ordinaria(Float.toString(h_ordi));
                lista.add(nuevo);
            }
            listaERROR=GestionPedidosDelegate.getInstance().importarAsistenciasDiarias(lista);
            if (listaERROR.isEmpty()){
                Utiles_MensajesDialogo.mensajeInfo("SE IMPORTARON LAS ASISTENCIAS SATISFACTORIAMENTE");
            }else{
                jdErroresImportacion error=new jdErroresImportacion(null,true);
                error.cargarData(listaERROR);
                error.setLocationRelativeTo(null);
                error.setVisible(true);
            }
        } catch (Exception ex) {
            Utiles_MensajesDialogo.mensajeError("No se pudo importar el archivo\n"+ex.getMessage());
            ex.printStackTrace();
            Logger.getLogger(jpImportarAsistencias.class.getName()).log(Level.SEVERE, null, ex);
        }
}//GEN-LAST:event_jbtnAceptarActionPerformed

    private void jbtnAceptarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jbtnAceptarKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER ){
            this.jbtnAceptar.doClick();
        }
}//GEN-LAST:event_jbtnAceptarKeyPressed

    private void jbtnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnCancelarActionPerformed
        int res = javax.swing.JOptionPane.showConfirmDialog( this,"Esta seguro de salir?",
                "Confirmar",javax.swing.JOptionPane.YES_NO_OPTION );
        if(res==javax.swing.JOptionPane.YES_OPTION){
            this.padre.dispose();
        }
}//GEN-LAST:event_jbtnCancelarActionPerformed
public void cargarExcel(){
        hojaExcel=0;
        ArrayList identificadores = null;
        ArrayList clases = null;
        Utiles_Importar ui = new Utiles_Importar( new File( this.jtfDireccion.getText().trim() ) );


            ui.setNumColumnas( 7 ); //Definimos que son 8 columnas
            dat = ui.getDatosHoja( this.hojaExcel ); //Definimos obtener los datos de la hoja 0
            identificadores = ui.getIdentificadores();
            clases = ui.getClases();
            filas=ui.getNumFilas()-1;

            boolean feriado=false,domingo=false;
            ArrayList datos;
             for(int i=0; i<dat.size(); i++){
                 datos= (ArrayList)(dat.get(i));
                 feriado=false;
                 domingo=false;
                 
                 if(datos.get(5).toString().toUpperCase().trim().startsWith("SI")){
                     feriado=true;
                 }
                 if(datos.get(6).toString().toUpperCase().trim().startsWith("SI")){
                     domingo=true;
                 }                 
                   ((javax.swing.table.DefaultTableModel)jtAsistencias.getModel()).addRow(
                           new Object[]{datos.get(0).toString(),datos.get(1).toString(),
                   datos.get(2).toString(),datos.get(3).toString(),datos.get(4).toString(),
                   feriado,domingo});
           }
     }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton jbtnAceptar;
    private javax.swing.JButton jbtnCancelar;
    private javax.swing.JButton jbtnMigrar;
    private javax.swing.JButton jbtnSeleccion;
    private javax.swing.JTable jtAsistencias;
    private javax.swing.JTextField jtfDireccion;
    // End of variables declaration//GEN-END:variables

}
